﻿package com.shuqi.common;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;

import com.shuqi.common.utils.Log4an;
import com.shuqi.model.net.HttpFactory;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;

/**
 * 异步加载图片
 */
public class AsyncImageLoader {
    private static final String logTag = "AsyncImageLoader";
    /** 图片类型：专题大图 */
    public static final int ImageType_MainTop = 0;
    /** 图片类型：封面图 */
    public static final int ImageType_BookCover = 1;
    /** 图片类型：启动图 */
    public static final int ImageType_LoadingPic = 2;

    private HashMap<String, SoftReference<Drawable>> imageCache;

    /** 初始化对象 */
    public AsyncImageLoader() {
        imageCache = new HashMap<String, SoftReference<Drawable>>();
    }

    /**
     * 获取图片
     * 
     * @param imageUrl
     * @param imageCallback
     * @param type 缓存的图片类型：AsyncImageLoader.ImageType_***
     * @param context applicationContext
     * @return
     */
    public Drawable loadDrawable(final String imageUrl, final ImageCallback imageCallback,
            final int type, final Context context, final String path) {
        if (imageCache.containsKey(imageUrl)) {
            SoftReference<Drawable> softReference = imageCache.get(imageUrl);
            Drawable drawable = null;
            try {
                // 反馈有遇到过空指针,无语
                drawable = softReference.get();
            } catch (Exception e) {
            }
            if (drawable != null) {
                return drawable;
            }
        }
        final Handler handler = new Handler() {
            @Override
            public void handleMessage(Message message) {
                if (imageCallback != null) {
                    imageCallback.imageLoaded((Drawable) message.obj, imageUrl);
                }
            }
        };
        new Thread() {
            @Override
            public void run() {
                Drawable drawable = loadImageFromUrl(imageUrl, type, context, path);
                if (drawable != null) {
                    imageCache.put(imageUrl, new SoftReference<Drawable>(drawable));
                    Message message = handler.obtainMessage(0, drawable);
                    handler.sendMessage(message);
                }
            }
        }.start();
        return null;
    }

    /**
     * 异步加载图片
     * 
     * @param url 图片地址
     * @param type 缓存图片的类型：AsyncImageLoader.ImageType_类型
     * @param context applicationContext
     * @return
     */
    public final static Drawable loadImageFromUrl(String url, int type, final Context context,
            String path) {
        try {
            if (url == null || "".equals(url)) {
                return null;
            }
            Drawable d = null;
            if (android.os.Environment.MEDIA_MOUNTED.equals(android.os.Environment
                    .getExternalStorageState())) {
                File folder = null;
                if (ImageType_LoadingPic == type) {
                    folder = new File(path);
                } else if (ImageType_BookCover == type) {
                    folder = new File(Config.DEFAULT_PATH_BOOKCOVER);
                } else {
                    folder = new File(Config.DEFAULT_PATH_COVER);
                }
                if (!folder.exists()) {
                    if (!folder.mkdirs()) {
                        URL m;
                        InputStream i = null;
                        try {
                            m = new URL(url);
                            i = (InputStream) m.getContent();
                        } catch (MalformedURLException e1) {
                            e1.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        d = Drawable.createFromStream(i, "src");
                        return d;
                    }
                }
                String name = url.substring(url.lastIndexOf("/") + 1, url.lastIndexOf("."));
                File imageFile = new File(folder, name);
                if (imageFile.exists()) {
                    d = Drawable.createFromPath(imageFile.getAbsolutePath());
                } else {
                    Log4an.e(logTag, "loadImageFromUrl() 下载图片 type:" + type + ",name=" + name);
                    imageFile = new File(folder, name + "_bak");
                    URL m;
                    InputStream i = null;
                    try {
                        m = new URL(url);
                        i = HttpFactory.getHttpURLConnectionFromURL(m, context).getInputStream();
                        FileOutputStream fos = new FileOutputStream(imageFile);
                        byte[] buffer = new byte[1024];
                        int size = 0;
                        while ((size = i.read(buffer)) != -1) {
                            fos.write(buffer, 0, size);
                        }
                        fos.flush();
                        i.close();
                        fos.close();
                        File newFile = new File(folder, name);
                        imageFile.renameTo(newFile);
                        d = Drawable.createFromPath(newFile.getAbsolutePath());
                    } catch (MalformedURLException e1) {
                        e1.printStackTrace();
                    } catch (IOException e) {
                        try {
                            if (imageFile != null)
                                imageFile.delete();
                        } catch (Exception e1) {
                            e1.printStackTrace();
                        }
                        e.printStackTrace();
                    }
                }
            } else {
                URL m;
                InputStream i = null;
                try {
                    m = new URL(url);
                    i = (InputStream) m.getContent();
                } catch (MalformedURLException e1) {
                    e1.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                d = Drawable.createFromStream(i, "src");
            }
            return d;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public interface ImageCallback {
        public void imageLoaded(Drawable imageDrawable, String imageUrl);
    }
}
